package com.baimifan.renovation.homefrag;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.LayoutDirection;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baimifan.renovation.DemoActivity;
import com.baimifan.renovation.R;
import com.baimifan.renovation.SearchActivity;
import com.baimifan.renovation.TaskActivity;
import com.baimifan.renovation.adapter.AddressFragAdapter;
import com.baimifan.renovation.adapter.DemoAdapter;
import com.baimifan.renovation.adapter.TaskAdapter;
import com.baimifan.renovation.adapter.TaskClassifyAdapter;
import com.baimifan.renovation.manager.BannerManager;
import com.baimifan.renovation.manager.DemoManager;
import com.baimifan.renovation.manager.TaskClassifyManager;
import com.baimifan.renovation.manager.TaskManager;
import com.baimifan.renovation.publicfrag.DialogFragmentWindow;
import com.baimifan.renovation.view.BannerViewHolder;
import com.flyco.tablayout.SlidingTabLayout;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.lang.ref.WeakReference;

/**
 * 首页-
 */
public class HomeFragment extends Fragment implements View.OnClickListener{
    private RelativeLayout rl_title;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private Activity home;
    private Float w, h, widthPixels, heightPixels;
    private MZBannerView home_banner;
    private ImageView viewTag_iv;
    private TextView viewTag_tag;
    private RecyclerView recyclerView, recyclerView2, recyclerView3;
    private View viewTag, viewTag2;
    private ImageView demo_iv1,demo_iv2;
    private TextView demo_tv1, demo_tv2;
    private ImageView hot_iv;
    private TextView hot_tv;
    private ImageView rl_iv;
    private TextView rl_city;
    private ImageView rl_tag;
    private LinearLayout home_rl;

    private MyHandler handler;
    private BannerManager bannerManager;
    private TaskClassifyManager taskClassifyManager;
    private DemoManager demoManager;
    private TaskManager taskManager;
    private TaskClassifyAdapter taskClassifyAdapter;

    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        home = getActivity();
        init(view);
        getDisplay();
        setLayoutParams();
        bannerManager.getBannner();
        taskClassifyManager.getTaskClassify();
        demoManager.getDemo();
        taskManager.getTask("");
        initLocation();
        return view;
    }

    private void init (View view) {
        home_rl = (LinearLayout) view.findViewById(R.id.home_rl);
        rl_city = (TextView) view.findViewById(R.id.rl_city);
        rl_tag = (ImageView) view.findViewById(R.id.rl_tag);
        rl_title = (RelativeLayout) view.findViewById(R.id.rl_title);
        home_banner = (MZBannerView) view.findViewById(R.id.home_banner);
        home_banner.setIndicatorVisible(false);
        home_banner.setDelayedTime(2000);
        viewTag_tag = (TextView) view.findViewById(R.id.home_viewTag_tag);
        viewTag_iv = (ImageView) view.findViewById(R.id.home_viewTag_iv);
        recyclerView = (RecyclerView) view.findViewById(R.id.home_recycler);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(home);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView2 = (RecyclerView) view.findViewById(R.id.home_recycler2);
        recyclerView2.setLayoutManager(new GridLayoutManager(home, 2));
        recyclerView3 = (RecyclerView) view.findViewById(R.id.home_recycler3);
        recyclerView3.setLayoutManager(new LinearLayoutManager(home));
        viewTag = view.findViewById(R.id.home_viewTag);
        viewTag2 = view.findViewById(R.id.home_viewTag2);
        demo_iv1 = (ImageView) view.findViewById(R.id.home_demo_iv1);
        demo_iv2 = (ImageView) view.findViewById(R.id.home_demo_iv2);
        demo_tv1 = (TextView) view.findViewById(R.id.home_demo_tv1);
        demo_tv2 = (TextView) view.findViewById(R.id.home_demo_tv2);
        hot_iv = (ImageView) view.findViewById(R.id.home_hot_iv);
        hot_tv = (TextView) view.findViewById(R.id.home_hot_tv);
        rl_iv = (ImageView) view.findViewById(R.id.rl_iv);
        handler = new MyHandler(this);
        bannerManager = new BannerManager(handler);
        taskClassifyManager = new TaskClassifyManager(handler);
        demoManager = new DemoManager(handler);
        taskManager = new TaskManager(handler);

        home_rl.setOnClickListener(this);
        rl_iv.setOnClickListener(this);
        demo_tv2.setOnClickListener(this);
        demo_iv2.setOnClickListener(this);
    }


    private void setLayoutParams () {
        LinearLayout.LayoutParams params_city = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_city.setMargins((int)(w*15), 0 ,0 ,0);
        params_city.gravity = Gravity.CENTER;
        rl_city.setLayoutParams(params_city);
        LinearLayout.LayoutParams params_city_tag = new LinearLayout.LayoutParams(
                (int)(w*14), (int)(h*7));
        params_city_tag.gravity = Gravity.CENTER;
        params_city_tag.setMargins((int)(w*2.5), 0 ,0 ,0);
        rl_tag.setLayoutParams(params_city_tag);
        RelativeLayout.LayoutParams params_rl_iv = new RelativeLayout.LayoutParams((int)(w*19), (int)(h*19));
        params_rl_iv.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params_rl_iv.setMargins(0, (int)(h*12.5), (int)(w*18.9), 0);
        rl_iv.setLayoutParams(params_rl_iv);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (h*44));
        rl_title.setLayoutParams(params);
        LinearLayout.LayoutParams params_banner = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (h*177));
        home_banner.setLayoutParams(params_banner);
        RelativeLayout.LayoutParams params_tag_iv = new RelativeLayout.LayoutParams(
                (int)(w*30), (int)(h*30));
        params_tag_iv.setMargins((int)(w*10),(int)(h*17),0,0);
        viewTag_iv.setLayoutParams(params_tag_iv);
        RelativeLayout.LayoutParams params_tag_tag = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_tag_tag.setMargins((int)(w*50),(int)(h*20),0,0);
        viewTag_tag.setLayoutParams(params_tag_tag);

        LinearLayout.LayoutParams params_re = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int)(h*72));
        params_re.setMargins(0, (int)(h*20), 0, (int)(h*15));
        recyclerView.setLayoutParams(params_re);

        LinearLayout.LayoutParams params_re2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_re2.setMargins((int)(h*15), (int)(h*18), (int)(h*15), (int)(h*15));
        recyclerView2.setLayoutParams(params_re2);

        LinearLayout.LayoutParams params_viewTag = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 12);
        viewTag.setLayoutParams(params_viewTag);
        viewTag2.setLayoutParams(params_viewTag);

        RelativeLayout.LayoutParams params_demo_iv1 = new RelativeLayout.LayoutParams((int)(w*30), (int)(h*30));
        params_demo_iv1.setMargins((int)(w*10), (int)(h*15), 0, 0);
        demo_iv1.setLayoutParams(params_demo_iv1);

        RelativeLayout.LayoutParams params_demo_iv2 = new RelativeLayout.LayoutParams((int)(w*10), (int)(h*15));
        params_demo_iv2.setMargins(0, (int)(h*22), (int)(w*15), 0);
        params_demo_iv2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        demo_iv2.setLayoutParams(params_demo_iv2);

        RelativeLayout.LayoutParams params_demo_tv1= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_demo_tv1.setMargins((int)(w*50), (int)(h*18), 0, 0);
        demo_tv1.setLayoutParams(params_demo_tv1);

        RelativeLayout.LayoutParams params_demo_tv2= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_demo_tv2.setMargins(0, (int)(h*19), (int)(w*36), 0);
        params_demo_tv2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        demo_tv2.setLayoutParams(params_demo_tv2);

        RelativeLayout.LayoutParams params_hot_iv= new RelativeLayout.LayoutParams((int)(w*30), (int)(h*30));
        params_hot_iv.setMargins((int)(w*10), (int)(h*17), 0, 0);
        hot_iv.setLayoutParams(params_hot_iv);

        RelativeLayout.LayoutParams params_hot_tv= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_hot_tv.setMargins((int)(w*50), (int)(h*19), 0, 0);
        hot_tv.setLayoutParams(params_hot_tv);

        LinearLayout.LayoutParams params_hot= new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params_hot.setMargins(0, (int)(h*15.6), 0, 0);
        recyclerView3.setLayoutParams(params_hot);
    }

    private void getDisplay() {
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        widthPixels = Float.valueOf(metrics.widthPixels);
        heightPixels = Float.valueOf(metrics.heightPixels);
        w = widthPixels / 360;
        h = heightPixels / 640;
    }

    /**
     * 高德定位
     */
    private void initLocation(){
        locationClient = new AMapLocationClient(home.getApplicationContext());
        locationOption = getDefaultOption();
        locationClient.setLocationOption(locationOption);
        locationClient.setLocationListener(locationListener);
        locationClient.startLocation();
    }

    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mOption.setGpsFirst(false);
        mOption.setHttpTimeOut(30000);
        mOption.setInterval(2000);
        mOption.setNeedAddress(true);
        mOption.setOnceLocation(true);
        mOption.setOnceLocationLatest(true);
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        mOption.setSensorEnable(false);
        mOption.setWifiScan(true);
        mOption.setLocationCacheEnable(true);
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                if(location.getErrorCode() == 0){
//                    Toast.makeText(home, location.getCity(), Toast.LENGTH_SHORT).show();
                } else {
//                    Toast.makeText(home, location.getErrorInfo(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(home, "定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        home_banner.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        home_banner.pause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_rl:
                DialogFragmentWindow dialogFragmentWindow = new DialogFragmentWindow();
                dialogFragmentWindow.show(getChildFragmentManager(), "");
                break;

            case R.id.rl_iv:
                Intent intent = new Intent(home, SearchActivity.class);
                home.startActivity(intent);
                break;

            case R.id.home_demo_tv2:
                home.startActivity(new Intent(home, DemoActivity.class));
                break;

            case R.id.home_demo_iv2:
                home.startActivity(new Intent(home, DemoActivity.class));
                break;
        }
    }


    private class MyHandler extends Handler {
        WeakReference<HomeFragment> mHome;

        public MyHandler (HomeFragment home) {
            mHome = new WeakReference<HomeFragment>(home);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final HomeFragment home = mHome.get();
            switch (msg.what) {
                case 1:
                    home_banner.setPages(bannerManager.geturls(), new MZHolderCreator<BannerViewHolder>() {
                        @Override
                        public BannerViewHolder createViewHolder() {
                            return new BannerViewHolder(w, h);
                        }
                    });
                    home_banner.start();
                    break;

                case 2:
                    taskClassifyAdapter = new TaskClassifyAdapter(taskClassifyManager.getClassify(), w, h);
                    recyclerView.setAdapter(taskClassifyAdapter);
                    taskClassifyAdapter.setOnItemListener(new TaskClassifyAdapter.OnItemClickListener() {
                        @Override
                        public void OnItemClick(int position) {
                            Intent intent = new Intent(home.getActivity(), TaskActivity.class);
                            intent.putExtra("catName", taskClassifyManager.getClassify().get(position).getCatName());
                            intent.putExtra("cId", taskClassifyManager.getClassify().get(position).getcId());
                            home.getActivity().startActivity(intent);
                        }
                    });
                    break;

                case 3:
                    recyclerView2.setAdapter(new DemoAdapter(demoManager.getDemos(), w, h));
                    break;

                case 4:
                    recyclerView3.setAdapter(new TaskAdapter(taskManager.gettasks(), w, h));
                    break;

            }
        }
    }
}
